<template>
  <div class="container">
    <div class="top">
      <el-input
        style="width: 200px; margin-bottom: 5px"
        v-model="search.searchCode"
        placeholder="请输入商品名称或编码"
        clearable
      >
      </el-input>
      <el-input
        style="width: 300px"
        :disabled="true"
        placeholder="请搜索类别信息"
        v-model="classNameList.name"
      >
        <template slot="prepend"
          >类别</template
        >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="classBtn"
        ></el-button>
      </el-input>

      <el-button
        size="small"
        type="primary"
        class="handleSearch"
        icon="el-icon-search"
        @click="handleSearch()"
        >查询
      </el-button>
      <el-button
        size="small"
        type="danger"
        class="handleSearch"
        icon="el-icon-delete"
        @click="empty()"
        >清空</el-button
      >
      <el-button
        type="info"
        size="small"
        icon="el-icon-tickets"
        @click="derive()"
        >导出</el-button
      >

      <el-button
        type="info"
        size="small"
        icon="el-icon-tickets"
        @click="derives()"
        >按加价导出</el-button
      >
      <el-button
        type="primary"
        size="small"
        class="handleSearch"
        icon="el-icon-upload"
        @click="downloads()"
        >箱规模板下载</el-button
      >
      <el-upload
        style="display: inline; margin-left: 10px"
        action="#"
        :show-file-list="false"
        :http-request="specHandleAvatarSuccess"
      >
        <el-button
          size="small"
          type="primary"
          class="handleSearch"
          icon="el-icon-circle-plus"
          >导入箱规</el-button
        >
      </el-upload>
      <el-button
        type="success"
        size="small"
        icon="el-icon-tickets"
        @click="priceInformation()"
        >加价信息导入</el-button
      >
      <el-button
        type="success"
        size="small"
        icon="el-icon-tickets"
        @click="priceReference()"
        >入库参考价导入</el-button
      >
    </div>
    <el-table
      max-height="600"
      :data="tableData"
      border
      style="width: 100%"
      empty-text="暂无数据"
    >
      <el-table-column
        prop="Name"
        label="商品名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="BarCode"
        label="条形码"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="Code"
        label="商品Code"
        align="center"
      ></el-table-column>
      <el-table-column label="商品别名" align="center" width="180">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.goods_alias"
            type="textarea"
            size="mini"
            @change="setName(scope)"
            placeholder="请输入别名"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="Code" label="入库箱规" align="center" width="180">
        <template slot-scope="scope">
          <el-input-number
            :controls="false"
            v-model="scope.row.rk_spec"
            size="mini"
            :min="0"
            controls-position="right"
            :precision="2"
            :step="1"
            @change="rebNum(scope)"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
        prop="Code"
        label="设置商品重量(KG)"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <el-input-number
            :controls="false"
            v-model="scope.row.weight"
            size="mini"
            :min="0"
            controls-position="right"
            :precision="4"
            :step="1"
            @change="weightNum(scope)"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
        prop="Code"
        label="设置商品体积(m³)"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <el-input-number
            :controls="false"
            v-model="scope.row.volume"
            size="mini"
            :min="0"
            controls-position="right"
            :precision="9"
            :step="1"
            @change="volumeNum(scope)"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
        prop="Code"
        label="皮重设置(KG)"
        align="center"
        width="180"
      >
        <template slot-scope="scope">
          <el-input-number
            :controls="false"
            v-model="scope.row.goods_tare"
            size="mini"
            :min="0"
            controls-position="right"
            :precision="4"
            :step="1"
            @change="tareNum(scope)"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
        prop="ClassName"
        label="分类"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="ClassCode"
        label="分类编码"
        align="center"
      ></el-table-column>
      <!-- <el-table-column
        prop="reference_price"
        label="入库参考价"
        align="center"
      ></el-table-column> -->
      <el-table-column
        prop="SalePrice"
        label="档案价格"
        align="center"
      ></el-table-column>
      <el-table-column label="加价" align="center" width="200px">
        <template slot-scope="scope">
          <div v-for="item in scope.row.all_percentage">
            <div>{{ item }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="商品所在位置" align="center" width="200px">
        <template slot-scope="scope">
          <div v-for="item in scope.row.all_shelves" :key="item">
            <div>{{ item }}</div>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column
        prop="CreateTime"
        label="添加时间"
        align="center"
      ></el-table-column> -->
      <el-table-column
        prop="SupplierName"
        label="供应商名称"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleGoodsShelves(scope)"
            >商品设置货架
          </el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="reference(scope)"
            >设置入库参考价
          </el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="examine(scope)"
            >商品二维码</el-button
          >
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleEdit(scope)"
            >设置商品加价</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="加价信息导入"
      :visible.sync="priceInformationDialog.centerDialogVisible"
      width="360px"
      center
    >
      <el-button type="primary" icon="el-icon-upload" @click="download()"
        >模板下载</el-button
      >
      <el-upload
        style="display: inline; margin-left: 10px"
        action="#"
        :show-file-list="false"
        :http-request="handleAvatarSuccess"
      >
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-circle-plus"
          >导入加价信息文件</el-button
        >
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="priceInformationDialog.centerDialogVisible = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="入库参考价导入"
      :visible.sync="priceReferenceDialog.centerDialogVisible"
      width="400px"
      center
    >
      <el-button
        type="primary"
        icon="el-icon-upload"
        @click="downloadReference()"
        >模板下载</el-button
      >
      <el-upload
        style="display: inline; margin-left: 10px"
        action="#"
        :show-file-list="false"
        :http-request="handleAvatarReferenceSuccess"
      >
        <el-button
          size="medium"
          type="primary"
          class="handleSearch"
          icon="el-icon-circle-plus"
          >导入入库参考价文件</el-button
        >
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="priceReferenceDialog.centerDialogVisible = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="商品二维码"
      :visible.sync="codedialog.centerDialogVisible"
      width="500px"
      center
    >
      <el-image
        style="width: 300px; height: 300px; display: block; margin: 0 auto"
        :src="codeUrl"
        fit="scale-down"
      ></el-image>
      <el-button
        type="primary"
        style="display: block; margin: 0 auto"
        icon="el-icon-download"
        @click="downloadImg()"
        >二维码图片下载</el-button
      >

      <span slot="footer" class="dialog-footer">
        <el-button @click="codedialog.centerDialogVisible = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>
    <!-- <el-dialog
      title="修改入库参考价"
      :visible.sync="referenceDialog.centerDialogVisible"
      width="360px"
      center
    >
      <el-form label-width="100px" label-position="left">
        <el-form-item label="入库参考价：">
          <el-input
            v-model="referenceCenter.reference_price"
            placeholder="请输入入库参考价"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="referenceDialog.centerDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="referenceConfirm()">确 定</el-button>
      </span>
    </el-dialog> -->
    <!-- 分页 -->
    <pagination
      @page="handleSizeChange"
      @pagesize="handleCurrentChange"
      :pageData="pageData"
    ></pagination>
    <addPercentageDialog
      @upData="getData"
      :dialog="dialog"
    ></addPercentageDialog>
    <addReferenceDialog
      @upData="getData"
      :dialog="referenceDialog"
    ></addReferenceDialog>
    <classDialog :classdialog="classdialog" @tag="classTag"></classDialog>
  </div>
</template>
<script>
import { parseTime } from "@/utils/index";
import { Loading } from "element-ui";
import Pagination from "@/components/pagination";
import {
  selectErpGoodsList,
  setReferencePrice,
  setGoodsSpec,
  setGoodsRatios,
  setGoodsAlias,
  setGoodsTare,
  setGoodsWeight,
  setGoodsVolume 
} from "@/api/commodity/commodityList";
import AddPercentageDialog from "@/components/commodity/addPercentageDialog";
import AddReferenceDialog from "@/components/commodity/addReferenceDialog";
import { getToken } from "@/utils/auth";
import ClassDialog from "@/components/superGrossMargin/classDialog";
export default {
  components: {
    pagination: Pagination,
    addPercentageDialog: AddPercentageDialog,
    addReferenceDialog: AddReferenceDialog,
    classDialog: ClassDialog
  },
  data() {
    return {
      //页面数据
      tableData: [],
      //分页
      pageData: {
        pageSizes: [10, 20],
        pageSize: 10,
        page: 1,
        total: null,
        layout: "total, sizes, prev, pager, next, jumper"
      },
      search: {
        searchCode: ""
      },
      dialog: {
        centerDialogVisible: false,
        code: "",
        id: ""
      },
      codedialog: {
        centerDialogVisible: false,
        code: ""
      },
      referenceDialog: {
        centerDialogVisible: false,
        code: "",
        id: ""
      },
      // referenceCenter: {
      //   reference_price: "",
      //   erp_goods_id: "",
      //   goods_code: "",
      // },
      classdialog: {
        centerDialogVisible: false
      },
      classNameList: {
        name: "",
        code: ""
      },
      codeUrl: "",
      priceInformationDialog: {
        centerDialogVisible: false
      },
      priceReferenceDialog: {
        centerDialogVisible: false
      }
    };
  },

  created() {
    //页面数据
    this.getData();
  },
  //监听当前页面返回事件
  beforeRouteLeave(to, from, next) {
    if (to.name == "goodsShelvesList") {
      from.meta.keepAlive = false;
    } else {
      from.meta.keepAlive = false;
      this.$destroy();
    }
    next();
  },
  methods: {
    //页面数据
    getData() {
      let data = {
        limit: this.pageData.pageSize,
        page: this.pageData.page,
        category_code: this.classNameList.code,
        goods_code: this.search.searchCode
      };
      selectErpGoodsList(data)
        .then(res => {
          if (res.code == 0) {
            // res.data.paginate.data.forEach((result) => {
            //   result.percentageMsg =
            //     result.type == 2 ? result.all_percentage + "%" : result.all_percentage;
            // });
            this.tableData = res.data.paginate.data;
            this.pageData.page = res.data.paginate.current_page;
            this.pageData.pagesize = res.data.paginate.per_page;
            this.pageData.total = res.data.paginate.total;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    classTag(data) {
      this.classNameList = {
        name: "",
        code: ""
      };
      console.log(data, 11111);
      let arrName = [];
      let arrCode = [];
      data.forEach(res => {
        arrName.push(res.name);
        arrCode.push(res.code);
      });
      this.classNameList.name = arrName.join(",");
      this.classNameList.code = arrCode.join(",");
    },
    //超级类别搜索
    classBtn() {
      this.classdialog = {
        centerDialogVisible: true
      };
    },
    //入库参考价确定
    // referenceConfirm() {
    //   if (this.referenceCenter.goods_code) {
    //     let data = {
    //       goods_code: this.referenceCenter.goods_code,
    //       erp_goods_id: this.referenceCenter.erp_goods_id,
    //       reference_price: this.referenceCenter.reference_price,
    //     };
    //     setReferencePrice(data).then((res) => {
    //       if (res.code == 0) {
    //         this.getData();
    //         this.referenceDialog.centerDialogVisible = false;
    //       }
    //     });
    //   } else {
    //     this.$message({
    //       type: "info",
    //       message: "请输入入库参考价",
    //     });
    //   }
    // },
    //修改入库参考价
    reference(scope) {
      this.referenceDialog.centerDialogVisible = true;
      this.referenceDialog.code = scope.row.Code;
      this.referenceDialog.id = scope.row.ProductId;
      // this.referenceCenter.goods_code = scope.row.Code;
      // this.referenceCenter.erp_goods_id = scope.row.ProductId;
      // this.referenceCenter.reference_price = scope.row.reference_price;
      // this.referenceDialog.centerDialogVisible = true;
    },

    examine(scope) {
      this.codedialog.centerDialogVisible = true;
      this.codedialog.code = scope.row.Code;
      this.codeUrl = `${
        this.$axios.defaults.baseURL
      }/api/Qrcode/getImg?content=${scope.row.Code}&token=${getToken()}`;
      console.log(this.codeUrl, 9999);
    },
    //二维码图片下载
    downloadImg() {
      let image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.src = this.codeUrl;
      image.onload = () => {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height);
        canvas.toBlob(blob => {
          let url = URL.createObjectURL(blob);
          let Link = document.createElement("a");
          Link.download = `${this.codedialog.code}`;
          Link.href = url;
          Link.click();
          Link.remove();
          // 用完释放URL对象
          URL.revokeObjectURL(url);
        });
      };
    },
    //设置商品加价
    handleEdit(scope) {
      this.dialog.centerDialogVisible = true;
      this.dialog.code = scope.row.Code;
      this.dialog.id = scope.row.ProductId;
    },
    //商品设置货架
    handleGoodsShelves(scope) {
      console.log(scope.row.house_code, 5555555);
      const vm = this;
      vm.$router.push({
        path: "/commodity/goodsShelvesList",
        query: { code: scope.row.Code }
      });
    },
    // 本地搜索
    handleSearch() {
      this.pageData.page = 1;
      this.pageData.total = null;
      this.getData();
    },
    //加价信息导入
    priceInformation() {
      this.priceInformationDialog.centerDialogVisible = true;
    },
    priceReference() {
      this.priceReferenceDialog.centerDialogVisible = true;
    },
    // 入库箱规
    rebNum(scope) {
      let data = {
        rk_spec: scope.row.rk_spec,
        goods_code: scope.row.Code,
        erp_goods_id: scope.row.ProductId
      };
      setGoodsSpec(data)
        .then(res => {
          console.log(res, 8899);
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: res.msg || res.message
            });
          } else {
            console.log(99999);
            this.$message({
              type: "error",
              message: res.msg || res.message
            });
            this.getData();
          }
        })
        .catch(err => {
          this.getData();
        });
    },
    //设置体积
    volumeNum(scope){
      let data = {
        volume: scope.row.volume,
        goods_code: scope.row.Code,
        erp_goods_id: scope.row.ProductId
      };
      setGoodsVolume(data).then(res => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: res.msg || res.message
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg || res.message
          });
          this.getData();
        }
      });
    },
    // 皮重设置
    tareNum(scope) {
      let data = {
        goods_tare: scope.row.goods_tare,
        goods_code: scope.row.Code,
        erp_goods_id: scope.row.ProductId
      };
      setGoodsTare(data).then(res => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: res.msg || res.message
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg || res.message
          });
          this.getData();
        }
      });
    },
    // 商品重量设置
    weightNum(scope) {
      let data = {
        weight: scope.row.weight,
        goods_code: scope.row.Code,
        erp_goods_id: scope.row.ProductId
      };
      setGoodsWeight(data).then(res => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: res.msg || res.message
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg || res.message
          });
          this.getData();
        }
      });
    },
    //导出
    derive() {
      this.$confirm("是否导出?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/goods/exportErpGoodsList?token=" +
            getToken() +
            "&category_code=" +
            this.classNameList.code +
            "&goods_code=" +
            this.search.searchCode;
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消导出"
          });
        });
    },
    //按加价导出
    derives() {
      this.$confirm("是否导出?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/goods/exportErpGoodsList?token=" +
            getToken() +
            "&percentage_export=1" +
            "&category_code=" +
            this.classNameList.code +
            "&goods_code=" +
            this.search.searchCode;
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消导出"
          });
        });
    },
    //下载模板
    download() {
      this.$confirm("是否下载模板?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/goods/downLoadPercentageTmp?token=" +
            getToken();
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //入库参考价下载模板
    downloadReference() {
      this.$confirm("是否下载模板?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/goods/downLoadReferencePriceTmp?token=" +
            getToken();
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //下载箱规模板
    downloads() {
      this.$confirm("是否下载箱规模板?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/goods/downLoadBoxSpecTmp?token=" +
            getToken();
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    specHandleAvatarSuccess(param) {
      let loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)"
      });
      let data = new window.FormData();
      data.append("ufile", param.file);
      data.append("token", getToken());
      this.$axios
        .post("/smkapi/goods/importGoodsSpec", data)
        .then(res => {
          loading.close();
          if (res.data.code == 0) {
            this.getData();
          } else {
            this.$message({
              type: "info",
              message: res.data.message || res.data.msg
            });
          }
        })
        .catch(err => {
          loading.close();
        });
    },
    //设置别名
    setName(scope) {
      let data = {
        goods_code: scope.row.Code,
        erp_goods_id: scope.row.ProductId,
        goods_alias: scope.row.goods_alias
      };
      console.log(data, 8888);
      setGoodsAlias(data).then(res => {
        console.log(res);
        if (res.code == 0) {
          this.$message({
            message: res.msg,
            type: "success"
          });
        }
      });
    },
    //导入商品
    handleAvatarSuccess(param) {
      let loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)"
      });
      let data = new window.FormData();
      data.append("percentage", param.file);
      data.append("token", getToken());
      this.$axios
        .post("/smkapi/goods/importPercentage", data)
        .then(res => {
          loading.close();
          if (res.data.code == 0) {
            this.priceInformationDialog.centerDialogVisible = false;
            this.getData();
          } else {
            this.$message({
              type: "info",
              message: res.data.message || res.data.msg
            });
          }
        })
        .catch(err => {
          loading.close();
        });
    },
    //导入入库参考价模本文件
    handleAvatarReferenceSuccess(param) {
      let loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)"
      });
      let data = new window.FormData();
      data.append("reference_price", param.file);
      data.append("token", getToken());
      this.$axios
        .post("/smkapi/goods/importReferencePrice", data)
        .then(res => {
          loading.close();
          if (res.data.code == 0) {
            this.priceInformationDialog.centerDialogVisible = false;
            this.getData();
          } else {
            this.$message({
              type: "info",
              message: res.data.message || res.data.msg
            });
          }
        })
        .catch(err => {
          loading.close();
        });
    },

    //清空
    empty() {
      this.classNameList.name = "";
      this.classNameList.code = "";
      this.search.searchCode = "";
    },
    //每页多少条
    handleCurrentChange(val) {
      this.pageData.page = 1;
      this.pageData.pageSize = val;

      this.getData();
    },
    //选取页数
    handleSizeChange(page) {
      this.pageData.page = page;

      this.getData();
    },
    //选取
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
};
</script>
<style scoped>
.top {
  position: relative;
}

.add {
  position: absolute;
  right: 0;
  top: 4px;
}

.pagination {
  text-align: right;
  padding: 10px;
}
</style>
